import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { ElMessage } from 'element-plus'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Main',
    meta: {
      title: '来做个题吧！'
    },
    component: () => import('../views/Home.vue')
  },
  {
    path: '/test',
    name: 'Test',
    meta: {
      title: '来做个题吧！'
    },
    component: () => import('../views/Test.vue')
  },
  {
    path: '/result',
    name: 'Result',
    meta: {
      title: '测试结果'
    },
    component: () => import('../views/Result.vue')
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '后台登录'
    },
    component: () => import('../views/Login.vue')
  },
  {
    path: '/admin',
    name: 'Admin',
    redirect: '/admin/home',
    component: () => import('../views/Main.vue'),
    children: [{
      path: 'home',
      name: 'Home',
      meta: {
        requireAuth: true,
        title: '后台管理'
      },
      component: () => import('../components/admin/Home.vue')
    }, {
      path: 'question',
      name: 'Question',
      meta: {
        requireAuth: true,
        title: '题库管理'
      },
      component: () => import('../components/admin/Question.vue')
    }, {
      path: 'test',
      name: 'TestList',
      meta: {
        requireAuth: true,
        title: '试题记录'
      },
      component: () => import('../components/admin/TestList.vue')
    }, {
      path: 'code',
      name: 'Code',
      meta: {
        requireAuth: true,
        title: '入群码管理'
      },
      component: () => import('../components/admin/Code.vue')
    }]
  }
]

const router = createRouter({
  history: createWebHistory('/group_review/'), // process.env.BASE_URL
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    document.title = to.meta.title
  }
  if (to.meta.requireAuth) {
    if (!sessionStorage.getItem('auth')) {
      ElMessage.error('请先登录')
      return next('/login')
    }
  }
  return next()
})

export default router
